//
//  PersonalViewController.m
//  Growth
//
//  Created by 洪波 陈 on 5/22/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "PersonalViewController.h"

#import "SDImageView+SDWebCache.h"

#import "TimelineUnitCell.h"

#import "GCDiscreetNotificationView.h"

//#define kTitleHeight    253
//#define kImageWidth     420
//#define kImageHeight    380

#define kTitleHeight    240
#define kImageWidth     320
#define kImageHeight    416



static ASIHTTPConnection *myMicroBlog_connect;

static ASIHTTPConnection *followUser_connect;

static ASIHTTPConnection *userRelation_connect;

static BOOL isDeleteFamilyRelation = NO;

@interface PersonalViewController (){
    
    int isFollow;
    
    NSString *userDisplayName;
}

@end

@implementation PersonalViewController

@synthesize notificationView;

@synthesize userInfoDict;
@synthesize userDiaryArray;

@synthesize userId;

@synthesize userRelationRequestStr;
@synthesize userDiaryRequsetStr;

@synthesize myTableView;

@synthesize familyRoleArray;
@synthesize userRelationDict;

//无权限界面
@synthesize privacyView;
@synthesize privacyActionView;
@synthesize privacyUserIcon;
@synthesize privacyUserNameLabel;
@synthesize privacyDetailLabel;
@synthesize  privacyStateLabel;

@synthesize privacyButton1;
@synthesize privacyButton2;
@synthesize privacyButton3;


//Unhandle
@synthesize relationUnhandleView;
@synthesize unhandleLabel1;
@synthesize unhandleLabel2;
@synthesize unhandleAcceptButton1;
@synthesize unhandleAcceptButton2;
@synthesize unhandleRejectButton1;
@synthesize unhandleRejectButton2;


- (void)dealloc
{
    [LoadingView hideWithAnimated:NO];
 
    [followButton release];
    
    if (myMicroBlog_connect != nil) {
        myMicroBlog_connect.connectionDelegate = nil;
        [myMicroBlog_connect release];
        myMicroBlog_connect = nil;
    }
    
       
    if (followUser_connect != nil) {
        
        followUser_connect.connectionDelegate = nil;
        [followUser_connect release];
        followUser_connect = nil;
    }
    
    [backGoundButton release];
    
    [userRelationDict release];
    
    [familyRoleArray release];
    
    [familyRoleLabel release];

    [userRelationRequestStr release];
    [userDiaryRequsetStr release];
    
    [privacyView release];
    [privacyActionView release];
    [privacyUserIcon release];
    [privacyUserNameLabel release];
    [privacyDetailLabel release];
    [privacyStateLabel release];
    
    [privacyButton1 release];
    [privacyButton2 release];
    [privacyButton3 release];
    
    
    
    [myTableView release];
    
          
    if (userRelation_connect != nil) {
        userRelation_connect.connectionDelegate = nil;
        [userRelation_connect release];
        userRelation_connect = nil;
    }
       
    
    CLog(@"Personal view dealloc!");
    
    [super dealloc];
}

- (id)initWithUserDict:(NSDictionary *)dict{
    self = [super init];
    if (self) {
        
        userInfoDict = dict;
    }
    return self;
    
}


- (id)initWithUserId:(int)uid userName:(NSString *)userName
{
    self = [super init];
    if (self) {
        self.userId = uid;
        userDisplayName = userName;
        
        CLog(@"Personal uid %d", uid);
    }
    
    
    if(self){
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillShow:) 
													 name:UIKeyboardWillShowNotification 
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillHide:) 
													 name:UIKeyboardWillHideNotification 
												   object:nil];		
	}

    
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    
       
    int selfUid = [[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
    if (selfUid == self.userId || userInfoDict != nil) {
        followButton.hidden = YES;
    }
    
    privacyUserIcon.layer.cornerRadius = 3;
    privacyUserIcon.clipsToBounds = YES;
    
    if (userInfoDict != nil) {
        privacyUserNameLabel.text =   [userInfoDict objectForKey:@"UserName"];

    }
    
    
    [followButton addTarget:self action:@selector(followUserAction:) forControlEvents:UIControlEventTouchUpInside];
    
   
    
    
    [self initGrowingTextView];

    
      userInfoConnectionState = kConnectionNone;
    userInfoDict = nil;

    userDiaryRequsetStr = nil;
    userRelationRequestStr = nil;
    
    userRelationIndex = 0;
    
    //初始化日志内容第一页
    pageNo = 1;
    
    if (userDiaryArray == nil) {
        userDiaryArray = [[NSMutableArray alloc] init];
    }
    
    [self loadData];
    
    
    [super viewDidLoad];
    [self refreshView];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    notificationView = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    //定义返回按钮
    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
    
    [self.navigationItem setBackBarButtonItem:backBarButtonItem];  
    [backBarButtonItem release]; 
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark LoadData

- (void)loadData{
    
    
    [self reloadUserDiary];
    
    int selfUid = [[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
    if (selfUid != self.userId) {
        [self loadUserRelation];
    }
  }



//获取权限完成后加载view 和其他数据
- (void)loadDataWith:(NSInteger)relationIndex
{
    
    //relation: 11 自己, 12 陌生人；
    //relation: 20 对方是我非正式家人，我未申请
    //relation: 21 对方是我正式家人，我未申请；
    //relation: 22 对方是我正式家人，我是对方正式家人；
    //relation: 23 对方是我正式家人，我是对方非正式家人；
    //relation: 24 对方是我非正式家人，我是对方正式家人；
    //relation: 25 对方是我非正式家人，我是对方非正式家人；
    //relation: 26 对方未申请，我是对方正式家人；
    //relation: 27 对方未申请，我是对方非正式家人；
    //relation: 31 好友,  32 等待好友同意, 33 接受好友邀请；
    //fid1: 我与对方家庭关系记录id；
    //fid2: 对方与我家庭关系记录id；
    //fid: 朋友关系记录id；
    
    //需要加载角色数据的关系id串
    NSString *needRoleDataStr = @"12,20,21,23,24,25,26,27";
    
    NSRange range = [needRoleDataStr rangeOfString:[NSString stringWithFormat:@"%d", relationIndex]];
    if (range.length >0) {
        [self loadFamilyRoleData ];
    }
    
}


- (void)loadUserRelation
{
    
    int selfUid = [[[NSUserDefaults standardUserDefaults]valueForKey:USER_ID] intValue];
   
    int friendId = userId;
    
    
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/CheckFollowRelationship.aspx?UserID=%d&FriendID=%d",BASEURL,userName,selfUid,friendId];
    NSURL *url = [NSURL URLWithString:urlString];
    
    if (userRelation_connect != nil) {
        
        userRelation_connect.connectionDelegate = nil;
        [userRelation_connect release];
        userRelation_connect = nil;
    }
    
    
    userRelation_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:NO];
    userRelation_connect.connectionDelegate = self;
    
    [userRelation_connect startAsynchronous];

    
}

- (void)reloadUserDiary
{
    if (userDiaryArray == nil) {
        userDiaryArray = [[NSMutableArray alloc]init];
    }
    
    [userDiaryArray removeAllObjects];
    
    [self loadUserDiary];
}

- (void)loadUserDiary
{

    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
   
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/MyMicroBlog.aspx?UserID=%d&pageNo=%d",BASEURL,userName,userId,pageNo];
	NSURL *url = [NSURL URLWithString:urlString];

    
    if (myMicroBlog_connect != nil) {
        myMicroBlog_connect.connectionDelegate = nil;
        [myMicroBlog_connect release];
        myMicroBlog_connect = nil;
    }
    
    myMicroBlog_connect = [[ASIHTTPConnection alloc]initGETWithURL:url resultDict:YES isCache:YES];
    myMicroBlog_connect.connectionDelegate = self;
    [myMicroBlog_connect startAsynchronous];
    [LoadingView showDefaultLoadingView];
    
    
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
    [self bottomRefDone];
    [self headerRefDone];
    [LoadingView hideWithAnimated:NO];
}
- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    
    [self bottomRefDone];
    [self headerRefDone];
    
    [LoadingView hideWithAnimated:YES];
    CLog(@"dict = %@",dict);
    
    NSString *urlStr = [url absoluteString];
    NSRange range = [urlStr rangeOfString:@"FollowUserInDomain"];
    if (range.length > 0) {
        
        
        return;
    }
    
    
    range = [urlStr rangeOfString:@"MyMicroBlog"];
    if (range.length > 0) {
        
        NSArray *array = [dict objectForKey:@"Records"];
        if (array.count > 0) {
            
            if (pageNo == 1) {
                [userDiaryArray removeAllObjects];
            }
            [userDiaryArray addObjectsFromArray:array];
            [self.myTableView reloadData];
            [self refreshView];
            
        }
        

    }
    
    
    range = [urlStr rangeOfString:@"CheckFollowRelationship"];
    if (range.length > 0) {
        
        if (dict) {
            if ([[dict objectForKey:@"isFollow"] boolValue]) {
                isFollow = 1;
                [followButton setTitle:@"取消关注" forState:UIControlStateNormal];
                            }
            else{
                isFollow = 0;
                [followButton setTitle:@"关注" forState:UIControlStateNormal];
            }
        }
        
    }
    

    
}



#pragma mark -
#pragma mark action

- (IBAction)editRelation:(id)sender
{
    CLog(@"编辑好友关系");
    //relation: 11 自己, 12 陌生人；
    //relation: 20 对方是我非正式家人，我未申请
    //relation: 21 对方是我正式家人，我未申请；
    //relation: 22 对方是我正式家人，我是对方正式家人；
    //relation: 23 对方是我正式家人，我是对方非正式家人；
    //relation: 24 对方是我非正式家人，我是对方正式家人；
    //relation: 25 对方是我非正式家人，我是对方非正式家人；
    //relation: 26 对方未申请，我是对方正式家人；
    //relation: 27 对方未申请，我是对方非正式家人；
    //relation: 31 好友,  32 等待好友同意, 33 接受好友邀请；
    //fid1: 我与对方家庭关系记录id；
    //fid2: 对方与我家庭关系记录id；
    //fid: 朋友关系记录id；
    

    NSInteger type = userRelationIndex /10;
    NSInteger typeIndex =userRelationIndex %10;
    
    NSString *userName = [userInfoDict objectForKey:@"userNickname"];
    NSString *detailStr;
    NSString *actionButtonTitle;
    
    switch (type) {
        case 2:
        {
            detailStr = [NSString stringWithFormat:@"你是否确定解除和“%@”的家人关系，关系解除后你们将不能彼此分享信息，请谨慎选择！", userName];
            actionButtonTitle = @"解除关系";
            break;
        }
        case 3:
        {
            detailStr = [NSString stringWithFormat:@"你是否确定解除和“%@”的好友关系，关系解除后你们将不能彼此分享信息，请谨慎选择！", userName];
            actionButtonTitle = @"解除关系";
            break;
        }
        default:
            return;
            break;
    }
    

    UIActionSheet *actionView = [[UIActionSheet alloc] initWithTitle:detailStr delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:actionButtonTitle, @"取消", nil];
    [actionView setCancelButtonIndex:1];
    [actionView showInView:self.view];
    
    [actionView release];
}





#pragma mark 取消关注
- (void)followUserAction:(id)sender{
    
    
    int friendID = userId;
    
    int isDeleteFollow = 0;
    if (isFollow == 1) {
        isDeleteFollow = 1;
        
    }
    
    int domainUserID = [[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/FollowUserInDomain.aspx?UserID=%d&FriendID=%d&isDeleteFollow=%d",BASEURL,userName,domainUserID,friendID,isDeleteFollow];
    NSURL *url = [NSURL URLWithString:urlString];
    
    if (followUser_connect != nil) {
        
        followUser_connect.connectionDelegate = nil;
        [followUser_connect release];
        followUser_connect = nil;
    }

    
    followUser_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:NO];
    followUser_connect.connectionDelegate = self;
    
    [followUser_connect startAsynchronous];
    
    [LoadingView showDefaultLoadingView];
    
    
    
}


#pragma mark - UIAction Sheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            //解除关系
            [self ignoreUserRelation:nil];
            isDeleteFamilyRelation = YES;
            break;
        }
        case 1:
        {
            break;
        }
        default:
            break;
    }
}

#pragma mark -
#pragma mark Load View
- (void)reLoadTableView
{
    //加载公用信息
    
    //如果有权限信息加载权限信息
    
    [self.myTableView reloadData];
}


//根据关系重新加载关系界面
- (void)loadRelationViewWith:(NSInteger)relationIndex
{
    
    //加为我的家人，加入他/她的家庭，加为好友
    //relation: 11 自己, 12 陌生人；
    //relation: 20 对方是我非正式家人，我未申请
    //relation: 21 对方是我正式家人，我未申请；
    //relation: 22 对方是我正式家人，我是对方正式家人；
    //relation: 23 对方是我正式家人，我是对方非正式家人；？
    //relation: 24 对方是我非正式家人，我是对方正式家人；？
    //relation: 25 对方是我非正式家人，我是对方非正式家人；？
    //relation: 26 对方未申请，我是对方正式家人；
    //relation: 27 对方未申请，我是对方非正式家人；
    //relation: 31 好友,  32 等待好友同意, 33 接受好友邀请；
    //fid1: 我与对方家庭关系记录id；
    //fid2: 对方与我家庭关系记录id；
    //fid: 朋友关系记录id；
    
    CLog(@"relation index %d", relationIndex);
    
    NSInteger type = relationIndex /10;
    NSInteger typeIndex =relationIndex %10;
    
    //清楚button的隐藏和事件
    privacyButton1.hidden = NO;
    privacyButton2.hidden = NO;
    privacyButton3.hidden = NO;
    privacyActionView.hidden = NO;
    
    privacyButton1.titleLabel.text = @"加为我的家人";
    privacyButton2.titleLabel.text = @"加入他的家庭";
    privacyButton3.titleLabel.text = @"   加为好友   ";
    
    //需要加载角色数据的关系id串
    NSString *needEditButtonDataStr = @"21,22,23,24,25,26,27,31,33";
    
    NSRange range = [needEditButtonDataStr rangeOfString:[NSString stringWithFormat:@"%d", relationIndex]];
    if (range.length >0) {
        //右侧功能按钮
        UIBarButtonItem *rightButtonIten = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(editRelation:)];
        
        [self.navigationItem setRightBarButtonItem:rightButtonIten];
        [rightButtonIten release];
    }
    else {
        [self.navigationItem setRightBarButtonItem:nil];
    }
    

    float privacyViewHeight = 117;
    
    
    
    switch (type) {
        case 0:
        {
            [privacyView setFrame:CGRectMake(0, 0, 320, 80)];
            privacyActionView.hidden = YES;
            break;
        }
        case 1:
        {
            // relation: 11 自己, 12 陌生人；
            switch (typeIndex) {
                case 1:
                {
                    //自己
                    [privacyView setFrame:CGRectMake(0, 0, 320, 80)];
                    privacyActionView.hidden = YES;
                    break;
                }
                case 2:
                {
                    //陌生人
                    //可做操作：邀请家人、申请家人、加为好友
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    
                    privacyButton1.enabled = YES;
                    privacyButton2.enabled = YES;
                    privacyButton3.enabled = YES;
                    
                    break;
                }
                default:
                    
                    break;
            }
            break;
        }
        case 2:
        {
            //relation: 20 对方是我非正式家人，我未申请
            //relation: 21 对方是我正式家人，我未申请；
            //relation: 22 对方是我正式家人，我是对方正式家人；
            //relation: 23 对方是我正式家人，我是对方非正式家人；
            //relation: 24 对方是我非正式家人，我是对方正式家人；
            //relation: 25 对方是我非正式家人，我是对方非正式家人；
            //relation: 26 对方未申请，我是对方正式家人；
            //relation: 27 对方未申请，我是对方非正式家人；
            //fid1: 我与对方家庭关系记录id；
            //fid2: 对方与我家庭关系记录id；
            switch (typeIndex) {
                case 0:
                {
                    //relation: 20 对方是我非正式家人，我未申请；
                    [privacyView setFrame:CGRectMake(0, 0, 320,privacyViewHeight)];
                    //privacyStateLabel.text = @"您已是对方家人，还可以邀请他/她加入您的家庭哦！";
                    
                    privacyButton1.enabled = NO;
                    privacyButton2.enabled = YES;
                    privacyButton3.enabled = NO;
                    
                }
                case 1:
                {
                    //relation: 21 对方是我正式家人，我未申请；
                    //可做操作：邀请家人，您已是对方家人
                    [privacyView setFrame:CGRectMake(0, 0, 320,privacyViewHeight)];
                    //privacyStateLabel.text = @"您已是对方家人，还可以邀请他/她加入您的家庭哦！";
                    
                    privacyButton1.enabled = NO;
                    privacyButton1.titleLabel.text = @"已是您的家人";
                    privacyButton2.enabled = YES;
                    privacyButton3.enabled = NO;

                    break;
                }
                case 2:
                {
                    //relation: 22 对方是我正式家人，我是对方正式家人；
                    //可做操作：申请家人，他/她已是您的家人
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    //privacyStateLabel.text = @"他/她已是您的家人，还可以申请成为他/她的家人哦！";
                    
                    privacyButton1.enabled = NO;
                    privacyButton1.titleLabel.text = @"已是您的家人";
                    privacyButton2.enabled = NO;
                    privacyButton2.titleLabel.text = @"已是他的家人";
                    privacyButton3.enabled = NO;

                    break;
                }
                case 3:
                {
                    //relation: 23 对方是我正式家人，我是对方非正式家人；
                    //互为家人
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    //privacyStateLabel.text = @"你们已是彼此的家人！";
                    
                    privacyButton1.enabled = NO;
                    privacyButton1.titleLabel.text = @"已是您的家人";
                    privacyButton2.enabled = NO;
                    privacyButton3.enabled = NO;
                    break;
                }
                case 4:
                {
                    //relation: 24 对方是我非正式家人，我是对方正式家人；
                    //可做操作：邀请家人，等待对方同意
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    //privacyStateLabel.text = @"您已申请/邀请成为对方家人，等待对方同意！";
                    privacyButton1.enabled = NO;
                    privacyButton2.enabled = NO;
                    privacyButton2.titleLabel.text = @"已是他的家人";
                    privacyButton3.enabled = NO;
                    

                    break;
                }
                case 5:
                {
                    //relation: 25 对方是我非正式家人，我是对方非正式家人；
                    //可做操作：申请家人，接受家人邀请
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    //privacyStateLabel.text = @"他/她邀请/申请您加入家庭，是否同意呢？";
                    
                    privacyButton1.enabled = NO;
                    privacyButton2.enabled = NO;
                    privacyButton3.enabled = NO;
                    
                    break;
                }
                case 6:
                {
                    //relation: 26 对方未申请，我是对方正式家人；
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    privacyButton1.enabled = YES;
                    privacyButton2.enabled = NO;
                    privacyButton2.titleLabel.text = @"已是他的家人";
                    privacyButton3.enabled = NO;
                    
                    break;
                    
                }
                case 7:
                {
                    //relation: 27 对方未申请，我是对方非正式家人；
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    privacyButton1.enabled = YES;
                    privacyButton2.enabled = NO;
                    privacyButton3.enabled = NO;
                    break;
                }
                    
                default:
                    break;
            }
            
            break;
        }
        case 3:
        {
            //relation: 31 好友,  32 等待好友同意, 33 接受好友邀请；
            //fid: 朋友关系记录id；
            switch (typeIndex) {
                case 1:
                {
                    //好友
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    //privacyStateLabel.text = @"你们是好友关系！";
                    
                    privacyButton1.enabled = NO;
                    privacyButton2.enabled = NO;
                    privacyButton3.enabled = NO;
                    privacyButton3.titleLabel.text = @"   已是好友   ";
                    
                    break;
                }
                case 2:
                {
                    // 等待好友同意
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    //privacyStateLabel.text = @"您已邀请对方成为好友，等待好友同意！";
                    
                    privacyButton1.enabled = NO;
                    privacyButton2.enabled = NO;
                    privacyButton3.enabled = NO;
                    privacyButton3.titleLabel.text = @"等待对方同意";
                    break;
                }
                case 3:
                {
                    //接受好友邀请
                    [privacyView setFrame:CGRectMake(0, 0, 320, privacyViewHeight)];
                    //privacyStateLabel.text = @"对方邀请您成为好友，是否接受呢？";
                    
                    privacyButton1.enabled = NO;
                    privacyButton2.enabled = NO;
                    privacyButton3.enabled = NO;
                    privacyButton3.titleLabel.text = @"等待您的同意";
                    break;
                }
                    
                default:
                    break;
            }
            
            break;
        }
        default:
            break;
    }
    
    
    //等待处理的关系事件
    [self unhandleRelationViewWith:relationIndex];
    
}

- (void)unhandleRelationViewWith:(NSInteger)relationIndex
{
    //加为我的家人，加入他/她的家庭，加为好友
    //relation: 11 自己, 12 陌生人；
    //relation: 20 对方是我非正式家人，我未申请
    //relation: 21 对方是我正式家人，我未申请；
    //relation: 22 对方是我正式家人，我是对方正式家人；
    //relation: 23 对方是我正式家人，我是对方非正式家人；？
    //relation: 24 对方是我非正式家人，我是对方正式家人；？
    //relation: 25 对方是我非正式家人，我是对方非正式家人；？
    //relation: 26 对方未申请，我是对方正式家人；
    //relation: 27 对方未申请，我是对方非正式家人；
    //relation: 31 好友,  32 等待好友同意, 33 接受好友邀请；
    //fid1: 我与对方家庭关系记录id；
    //fid2: 对方与我家庭关系记录id；
    //fid: 朋友关系记录id；
    
    CLog(@"unhandleRelationViewWith relation index %d", relationIndex);
    
    NSInteger type = relationIndex /10;
    NSInteger typeIndex =relationIndex %10;
    

    unhandleLabel1.text = nil;
    unhandleLabel2.text = nil;
    [unhandleAcceptButton1 removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];
    [unhandleAcceptButton2 removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];
    [unhandleRejectButton1 removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];
    [unhandleRejectButton2 removeTarget:nil action:nil forControlEvents:UIControlEventAllEvents];
    
    [relationUnhandleView removeFromSuperview];

    
    switch (type) {
        case 2:
        {
            //relation: 20 对方是我非正式家人，我未申请
            //relation: 21 对方是我正式家人，我未申请；
            //relation: 22 对方是我正式家人，我是对方正式家人；
            //relation: 23 对方是我正式家人，我是对方非正式家人；
            //relation: 24 对方是我非正式家人，我是对方正式家人；
            //relation: 25 对方是我非正式家人，我是对方非正式家人；
            //relation: 26 对方未申请，我是对方正式家人；
            //relation: 27 对方未申请，我是对方非正式家人；
            //fid1: 我与对方家庭关系记录id；
            //fid2: 对方与我家庭关系记录id；
            switch (typeIndex) {
                case 0:
                {
                    //relation: 20 对方是我非正式家人，我未申请；
                    NSString *actionCode = [userRelationDict objectForKey:@"fid1Action"];
                    NSString *fidStr = [self.userRelationDict objectForKey:@"fid1"];
                    if (![fidStr isMemberOfClass:[NSNull class]]
                        && ![actionCode isMemberOfClass:[NSNull class]])
                    {
                        if ([actionCode isEqualToString:@"invite"]) {
                            //是不是给提示
                            privacyButton1.titleLabel.text = @"等待对方同意";
                            [relationUnhandleView removeFromSuperview];
                        }
                        else if([actionCode isEqualToString:@"apply"]){
                            privacyButton1.titleLabel.text = @"等待您的同意";
                            
                            if (relationUnhandleView.superview == nil) {
                                [self.view addSubview:relationUnhandleView];
                            }
                            [relationUnhandleView setFrame:CGRectMake(87, 0, 146, 55)];
                            
                            unhandleLabel1.text = @"申请加入您的家庭";
                            unhandleAcceptButton1.tag = [fidStr intValue];
                            unhandleRejectButton1.tag = [fidStr intValue];
                            [unhandleAcceptButton1 addTarget:self action:@selector(acceptFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                            [unhandleRejectButton1 addTarget:self action:@selector(ignoreFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                        }
                    }
                }
                case 3:
                {
                    //relation: 23 对方是我正式家人，我是对方非正式家人；
                    //互为家人
                    NSString *actionCode = [userRelationDict objectForKey:@"fid2Action"];
                    NSString *fidStr = [self.userRelationDict objectForKey:@"fid2"];
                    if (![fidStr isMemberOfClass:[NSNull class]]
                        && ![actionCode isMemberOfClass:[NSNull class]])
                    {
                        if ([actionCode isEqualToString:@"apply"]) {
                            privacyButton2.titleLabel.text = @"等待对方同意";
                            //是不是给提示
                            [relationUnhandleView removeFromSuperview];
                        }
                        else if([actionCode isEqualToString:@"invite"]){
                            privacyButton2.titleLabel.text = @"等待您的同意";
                            if (relationUnhandleView.superview == nil) {
                                [self.view addSubview:relationUnhandleView];
                            }
                            [relationUnhandleView setFrame:CGRectMake(87, 0, 146, 55)];
                            
                            unhandleLabel1.text = @"邀请您加入他/她的家庭";
                            unhandleAcceptButton1.tag = [fidStr intValue];
                            unhandleRejectButton1.tag = [fidStr intValue];
                            [unhandleAcceptButton1 addTarget:self action:@selector(acceptFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                            [unhandleRejectButton1 addTarget:self action:@selector(ignoreFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                        }
                    }
                    break;
                }
                case 4:
                {
                    //relation: 24 对方是我非正式家人，我是对方正式家人；
                    NSString *actionCode = [userRelationDict objectForKey:@"fid1Action"];
                    NSString *fidStr = [self.userRelationDict objectForKey:@"fid1"];
                    if (![fidStr isMemberOfClass:[NSNull class]]
                        && ![actionCode isMemberOfClass:[NSNull class]])
                    {
                        if ([actionCode isEqualToString:@"invite"]) {
                            privacyButton1.titleLabel.text = @"等待对方同意";
                            //是不是给提示
                            [relationUnhandleView removeFromSuperview];
                        }
                        else if([actionCode isEqualToString:@"apply"]){
                            privacyButton1.titleLabel.text = @"等待您的同意";
                            if (relationUnhandleView.superview == nil) {
                                [self.view addSubview:relationUnhandleView];
                            }
                            [relationUnhandleView setFrame:CGRectMake(87, 0, 146, 55)];
                            
                            unhandleLabel1.text = @"申请加入您的家庭";
                            unhandleAcceptButton1.tag = [fidStr intValue];
                            unhandleRejectButton1.tag = [fidStr intValue];
                            [unhandleAcceptButton1 addTarget:self action:@selector(acceptFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                            [unhandleRejectButton1 addTarget:self action:@selector(ignoreFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                        }
                    }
                    
                    break;
                }
                case 5:
                {
                    //relation: 25 对方是我非正式家人，我是对方非正式家人；
                    NSString *actionCode1 = [userRelationDict objectForKey:@"fid1Action"];
                    NSString *fidStr1 = [self.userRelationDict objectForKey:@"fid1"];
                    if (![fidStr1 isMemberOfClass:[NSNull class]]
                        && ![actionCode1 isMemberOfClass:[NSNull class]])
                    {
                        if ([actionCode1 isEqualToString:@"invite"]) {
                            privacyButton1.titleLabel.text = @"等待对方同意";
                            //是不是给提示
                            [relationUnhandleView removeFromSuperview];
                            
                            
                            NSString *actionCode2 = [userRelationDict objectForKey:@"fid2Action"];
                            NSString *fidStr2 = [self.userRelationDict objectForKey:@"fid2"];
                            if (![fidStr2 isMemberOfClass:[NSNull class]]
                                && ![actionCode2 isMemberOfClass:[NSNull class]])
                            {
                                if ([actionCode2 isEqualToString:@"apply"]) {
                                    privacyButton2.titleLabel.text = @"等待对方同意";
                                    //是不是给提示
                                    [relationUnhandleView removeFromSuperview];
                                }
                                else if([actionCode2 isEqualToString:@"invite"]){
                                    privacyButton2.titleLabel.text = @"等待您的同意";
                                    if (relationUnhandleView.superview == nil) {
                                        [self.view addSubview:relationUnhandleView];
                                    }
                                    [relationUnhandleView setFrame:CGRectMake(87, 0, 146, 55)];
                                    
                                    unhandleLabel1.text = @"邀请您加入他/她的家庭";
                                    unhandleAcceptButton1.tag = [fidStr1 intValue];
                                    unhandleRejectButton1.tag = [fidStr1 intValue];
                                    [unhandleAcceptButton1 addTarget:self action:@selector(acceptFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                                    [unhandleRejectButton1 addTarget:self action:@selector(ignoreFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                                }
                            }
                            
                        }
                        else if([actionCode1 isEqualToString:@"apply"]){
                            privacyButton1.titleLabel.text = @"等待您的同意";
                            if (relationUnhandleView.superview == nil) {
                                [self.view addSubview:relationUnhandleView];
                            }
                            [relationUnhandleView setFrame:CGRectMake(87, 0, 146, 55)];
                            unhandleLabel1.text = @"申请加入您的家庭";
                            unhandleAcceptButton1.tag = [fidStr1 intValue];
                            unhandleRejectButton1.tag = [fidStr1 intValue];
                            [unhandleAcceptButton1 addTarget:self action:@selector(acceptFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                            [unhandleRejectButton1 addTarget:self action:@selector(ignoreFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                            
                            
                            
                            NSString *actionCode2 = [userRelationDict objectForKey:@"fid2Action"];
                            NSString *fidStr2 = [self.userRelationDict objectForKey:@"fid2"];
                            if (![fidStr2 isMemberOfClass:[NSNull class]]
                                && ![actionCode2 isMemberOfClass:[NSNull class]])
                            {
                                if ([actionCode2 isEqualToString:@"apply"]) {
                                    //是不是给提示
                                    privacyButton2.titleLabel.text = @"等待对方同意";
                                }
                                else if([actionCode2 isEqualToString:@"invite"]){
                                    privacyButton2.titleLabel.text = @"等待您的同意";
                                    if (relationUnhandleView.superview == nil) {
                                        [self.view addSubview:relationUnhandleView];
                                    }
                                    [relationUnhandleView setFrame:CGRectMake(87, 0, 146, 104)];
                                    
                                    unhandleLabel2.text = @"邀请您加入他/她的家庭";
                                    unhandleAcceptButton2.tag = [fidStr2 intValue];
                                    unhandleRejectButton2.tag = [fidStr2 intValue];
                                    [unhandleAcceptButton2 addTarget:self action:@selector(acceptFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                                    [unhandleRejectButton2 addTarget:self action:@selector(ignoreFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                                }
                            }
                            
                            
                        }
                    }
                    
                    break;
                }
                case 7:
                {
                    //relation: 27 对方未申请，我是对方非正式家人；
                    NSString *actionCode = [userRelationDict objectForKey:@"fid2Action"];
                    NSString *fidStr = [self.userRelationDict objectForKey:@"fid2"];
                    if (![fidStr isMemberOfClass:[NSNull class]]
                        && ![actionCode isMemberOfClass:[NSNull class]])
                    {
                        if ([actionCode isEqualToString:@"apply"]) {
                            privacyButton2.titleLabel.text = @"等待对方同意";
                            //是不是给提示
                            [relationUnhandleView removeFromSuperview];
                        }
                        else if([actionCode isEqualToString:@"invite"]){
                            privacyButton2.titleLabel.text = @"等待您的同意";
                            if (relationUnhandleView.superview == nil) {
                                [self.view addSubview:relationUnhandleView];
                            }
                            [relationUnhandleView setFrame:CGRectMake(87, 0, 146, 55)];
                            
                            unhandleLabel1.text = @"邀请您加入他/她的家庭";
                            unhandleAcceptButton1.tag = [fidStr intValue];
                            unhandleRejectButton1.tag = [fidStr intValue];
                            [unhandleAcceptButton1 addTarget:self action:@selector(acceptFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                            [unhandleRejectButton1 addTarget:self action:@selector(ignoreFamilyInvite:) forControlEvents:UIControlEventTouchUpInside];
                        }
                    }

                    break;
                }
                    
                default:
                    break;
            }
            
            break;
        }
        case 3:
        {
            //relation: 31 好友,  32 等待好友同意, 33 接受好友邀请；
            //fid: 朋友关系记录id；
            switch (typeIndex) {
                case 2:
                {
                    // 等待好友同意
                    [relationUnhandleView removeFromSuperview];
                    break;
                }
                case 3:
                {
                    //接受好友邀请

                    NSString *fidStr = [self.userRelationDict objectForKey:@"fid"];
                    if (![fidStr isMemberOfClass:[NSNull class]])
                    {
                        if (relationUnhandleView.superview == nil) {
                            [self.view addSubview:relationUnhandleView];
                        }
                        [relationUnhandleView setFrame:CGRectMake(87, 0, 146, 55)];
                        
                        unhandleLabel1.text = @"邀请您成为他/她的好友";
                        unhandleAcceptButton1.tag = [fidStr intValue];
                        unhandleRejectButton1.tag = [fidStr intValue];
                        [unhandleAcceptButton1 addTarget:self action:@selector(acceptFreindInvite:) forControlEvents:UIControlEventTouchUpInside];
                        [unhandleRejectButton1 addTarget:self action:@selector(ignoreFriendInvite:) forControlEvents:UIControlEventTouchUpInside];
                    }
                    
                    break;
                }
                    
                default:
                    break;
            }
            
            break;
        }
        default:
         {       
            [relationUnhandleView removeFromSuperview];
            break;
         }
    }
}

#pragma mark -
#pragma mark Connection Delegate
- (void)connectionSuccess:(NSDictionary *)dict
{
    [LoadingView hideWithAnimated:YES];
    
    CLog(@"User info dict %@", dict);
    NSString *uid = [dict objectForKey:@"userId"];
    if (uid != nil) {
        [userInfoLoadingActivity stopAnimating];
        userInfoLoadingActivity.hidden = YES;
        
        userInfoDict = [[NSDictionary alloc] initWithDictionary:dict];
        userInfoConnectionState = kConnectionDoneSuccess;
        
        if (![[userInfoDict objectForKey:@"timelineNum"] isMemberOfClass:[NSNull class]]) {
            
            if ([[userInfoDict objectForKey:@"timelineNum"] intValue] > 0) {
                
                if (![[[[userInfoDict objectForKey:@"timelineViews"] objectAtIndex:0] objectForKey:@"coverPhoto"] isMemberOfClass:[NSNull class]]) {
                    
                    int imageId = [[[[userInfoDict objectForKey:@"timelineViews"] objectAtIndex:0] objectForKey:@"coverPhoto"] intValue];
                    
                    NSString *string=[NSString stringWithFormat:@"%@%@/%d/480x480",BASEURL,@"/commons/attachment/download",imageId];
                    NSURL *url = [NSURL URLWithString:string];	
                    
                    //图片存储分类
                    
                     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"labbao_tree_iphone" ofType:@"jpg"];
                    
                    [covorImageView setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageWithContentsOfFile:filePath] imageType:kImageCache_Content_Browse];
                    
                }
 
            }

        }
        
        self.navigationItem.title = [userInfoDict objectForKey:@"userNickname"];
        
        [self reLoadTableView];
    }
    else {
        userInfoDict = nil;
        userInfoConnectionState = kConnectionDoneError;
    }
    
       
    
}
- (void)connectionError:(NSError *)error
{
    [LoadingView hideWithAnimated:YES];
    userInfoConnectionState = kConnectionDoneError;
}

- (void)postSuccess:(NSString *)postinfo
{
    [LoadingView hideWithAnimated:YES];
    
}

- (void)connectionArraySuccess:(NSDictionary *)dict  connectionURL:(NSString *)url
{
    CLog(@"dict array %@", dict);
    [LoadingView hideWithAnimated:YES];
    
    //私信
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/inbox/send",BASEURL]]) {
        
        [LoadingView showDurationMessageLoadingViewWith:20 message:@"已发送到对方信箱"];
        return;
        
    }
    
    
    
    
    //家人角色
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/family/role",BASEURL]]) {
        
        self.familyRoleArray = [dict objectForKey:@"object"];
        
        return;
        
    }
    
    
    NSRange range = [url rangeOfString:@"obile/friend/invite"];
    //添加好友
    if (range.length > 0) {
        
        BOOL isSuccess = [[dict objectForKey:@"object"] boolValue];
        
        if (isSuccess) {
            [self loadUserRelation];
            [LoadingView showImage:[UIImage imageNamed:@"wangluo_success_iphone.png"] info:@"添加成功，等待对方同意！" duration:DEFAULT_LOADING_TIME];
        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"处理失败，请重试！"];
        }
        return;  
    }
    
    //添加家人——邀请
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/family/invite",BASEURL]]) {
        
        BOOL isSuccess = [[dict objectForKey:@"object"] boolValue];
        
        if (isSuccess) {
            [self loadUserRelation];
            [LoadingView showImage:[UIImage imageNamed:@"wangluo_success_iphone.png"] info:@"邀请成功，等待对方同意！" duration:DEFAULT_LOADING_TIME ];
        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"处理失败，请重试！"];
        }
        return; 
    }
    
    //申请
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/family/apply",BASEURL]]) {
        BOOL isSuccess = [[dict objectForKey:@"object"] boolValue];
        
        if (isSuccess) {
            [self loadUserRelation];
            [LoadingView showImage:[UIImage imageNamed:@"wangluo_success_iphone.png"] info:@"申请成功，等待对方同意！" duration:DEFAULT_LOADING_TIME];
        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"处理失败，请重试！"];
        }
        return; 
    }

    
    //url 截取处理
    range = [url rangeOfString:@"?" options:1];
    NSString *subUrl = [url substringToIndex:range.location];
    
    //接受好友邀请
    if ([subUrl isEqualToString:[NSString stringWithFormat:@"%@/mobile/friend/accept",BASEURL]]) {
        
        BOOL isSuccess = [[dict objectForKey:@"object"] boolValue];
        
        if (isSuccess) {//接受邀请成功,查看日志内容
            [self loadUserRelation]; 
        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"处理失败，请重试！"];
        }
        return;
    }  
    
    //忽略好友邀请
    if ([subUrl isEqualToString:[NSString stringWithFormat:@"%@/mobile/friend/ignore",BASEURL]]) {
        
        BOOL isSuccess = [[dict objectForKey:@"object"] boolValue];
        
        if (isSuccess) {//接受邀请成功,查看日志内容
            
            [self loadUserRelation];
            
            
        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"处理失败，请重试！"];
        }
        return;
    }
                  
    //接受家人邀请    
    if ([subUrl isEqualToString:[NSString stringWithFormat:@"%@/mobile/family/accept",BASEURL]]) {
        
        BOOL isSuccess = [[dict objectForKey:@"object"] boolValue];
        
        if (isSuccess) {//接受邀请成功,查看日志内容
            [self loadUserRelation];
            
        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"处理失败，请重试！"];
        }
        return;
    }  
    
    //忽略家人邀请/申请
    if ([subUrl isEqualToString:[NSString stringWithFormat:@"%@/mobile/family/ignore",BASEURL]]) {
        
        BOOL isSuccess = [[dict objectForKey:@"object"] boolValue];
        
        if (isSuccess) {//接受邀请成功,查看日志内容
            [self loadUserRelation];
            

        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"处理失败，请重试！"];
        }
        return;
    }

    //用户关系获取
    if ([subUrl isEqualToString:userRelationRequestStr]) {
        
        CLog(@"user relation dict :%@", dict);
        
        self.userRelationDict = [dict objectForKey:@"object"];
        userRelationIndex = [[self.userRelationDict objectForKey:@"relation"] intValue];
        
        CLog(@"Relation index %d ", userRelationIndex);
        
        [self loadDataWith:userRelationIndex];
        
        [self loadRelationViewWith:userRelationIndex];
        
        [self reLoadTableView];
        
    }
    else if([subUrl isEqualToString:userDiaryRequsetStr]){
        //日志获取
        NSArray *objectArray = [dict objectForKey:@"object"];
        
        [diaryLoadingActivity stopAnimating];
        diaryLoadingActivity.hidden = YES;
        
        if (userDiaryArray == nil) {
            userDiaryArray = [[NSMutableArray alloc]init];
        }

        if ([objectArray count] != 0) {
            [userDiaryArray addObjectsFromArray:objectArray];
            CLog(@"User diary %@ ", objectArray);
            
            [self reLoadTableView];
        }
 
        //table 上拉刷新
        if (_refreshTailView == nil) {
            
             CLog(@"contentSize %f",self.myTableView.contentSize.height);
            
            _refreshTailView = [[EGORefreshTableTailView alloc] initWithFrame:CGRectMake(0.0f, self.myTableView.contentSize.height, 320, 650)];
            _refreshTailView.delegate = self;
                       
            [self.myTableView addSubview:_refreshTailView];
                       
        }

        if(_refreshTailView != nil){
            
            int height = self.myTableView.contentSize.height > 420 ? self.myTableView.contentSize.height:420 ;
            
            CLog(@"contentSize %f",self.myTableView.contentSize.height);
            
            
            
             [_refreshTailView setFrame:CGRectMake(0.0f, height, 320, 650)];    
        
             [_refreshTailView refreshLastUpdatedDate];

        }
        
               
    }
    
    [self doneLoadingTableViewData];
    
}
- (void)connectionArrayError:(NSError *)error
{
    [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME *1.2];
    
    CLog(@"Personal connection array error");
}

#pragma mark -
#pragma mark Table 下拉刷新



#pragma mark - 
#pragma mark TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (userDiaryArray.count == 0) {
        
        return 1;
    }
    else{
    
    return 1 +[userDiaryArray count];
    }


}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    NSInteger row = indexPath.row;
    
    if (row == 0) {
        
        
        static NSString *CellIdentifier = @"CellIdentifier11";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            
            [cell addSubview:privacyView];
            
            
            [cell setBackgroundColor:[UIColor clearColor]];
            
        }
        
     
            
            privacyView.hidden = NO;
        
        if (userDisplayName != nil) {
            
            privacyUserNameLabel.text = userDisplayName;

        }
                      
            
        
              
        //cell.contentView.backgroundColor = BackGround_Color;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
    else if (row >0) {  ///日志列表
        
        static NSString *MyIdentifier = @"TimelineUnitCell111";
        
        // Try to retrieve from the table view a now-unused cell with the given identifier.
        TimelineUnitCell *cell =(TimelineUnitCell *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        
		if (cell == nil) {                
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TimelineUnitCell" 
                                                         owner:self options:nil];
#ifdef __IPHONE_2_1
            cell = (TimelineUnitCell *)[nib objectAtIndex:0];
#else
            cell = (TimelineUnitCell *)[nib objectAtIndex:1];
#endif
            
            cell.delegate = self;
            
                      
            
            
        }
        else {
            UIImageView* oldImage = (UIImageView*)
            [cell.contentView viewWithTag:999];
            if(oldImage)
                [oldImage removeFromSuperview];
        }
        
        
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        
        if (self.userDiaryArray.count>0) {
            
            NSMutableDictionary *dict;
            dict = [self.userDiaryArray objectAtIndex:row - 1];
           
            [cell loadCellViewWith:dict ];
            [cell initNewsIconButton:dict];
            
            
        }
        
               
        return cell;
        
        
    }
 
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger row = indexPath.row;
    
    switch (row) {
        case 0:
        {

           return privacyView.frame.size.height;

            break;
        }
       
        default:
        {
            
            UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
                            
            return cell.frame.size.height;
                      
            break;
        }
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    int row = indexPath.row;
    
    if (row > 1 && userDiaryArray.count >0) {
        
        TLDetailViewContentViewController * detailViewController =   [[TLDetailViewContentViewController alloc] initWithPost:[self.userDiaryArray objectAtIndex:indexPath.row-2] page:indexPath.row-1 conttentType:@"TLTrend_friends"];
        
        
        GrowthAppDelegate *appDelegate = 
        (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
        
        [self.navigationController pushViewController:detailViewController animated:YES];
        
        [detailViewController release];
        
    }
    
    
 

    
}
#pragma mark -
#pragma mark Table 下拉刷新
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods


- (void)refreshView
{
    
    //顶部刷新条
    if ( _refreshHeaderView == nil) {
        
        _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f- self.myTableView.bounds.size.height, 320, self.myTableView.bounds.size.height)];
        _refreshHeaderView.delegate = self;
        [self.myTableView addSubview:_refreshHeaderView];
    }
    
    
    //底部刷新条
    if ( _refreshTailView == nil) {
        
        _refreshTailView = [[EGORefreshTableTailView alloc] initWithFrame:CGRectMake(0.0f, self.myTableView.contentSize.height, 320, self.myTableView.frame.size.height)];
        _refreshTailView.delegate = self;
        [self.myTableView addSubview:_refreshTailView];
        
    }
    
    if (_refreshTailView != nil) {
        float height = MAX(self.myTableView.contentSize.height, self.myTableView.frame.size.height);
        [_refreshTailView setFrame:CGRectMake(0.0f, height, 320, self.myTableView.frame.size.height)];
    }
    
    
}



//顶部刷新事件
- (void)headerRefData
{
    _HeaderReloading = YES;
    pageNo = 1;
    [self loadData];
    
}

- (void)headerRefDone
{
    _HeaderReloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
}

//底部刷新事件
- (void)bottomRefData
{
    
    
    _TailReloading = YES;
    
    pageNo = userDiaryArray.count/20 +1;
    
    [self loadData];
    
}

- (void)bottomRefDone
{
    _TailReloading = NO;
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
    }
    
}



#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
    //上拉
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
    
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    //上拉
    if (_refreshTailView != nil) {
        
        [_refreshTailView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
}


#pragma mark -
#pragma mark EGORefreshTableTailDelegate Methods

- (void)egoRefreshTableTailDidTriggerRefresh:(EGORefreshTableTailView*)view{
	
	[self bottomRefData];
    
}

- (BOOL)egoRefreshTableTailDataSourceIsLoading:(EGORefreshTableTailView*)view{
	
    
    return _TailReloading;
	
}

- (NSDate*)egoRefreshTableTailDataSourceLastUpdated:(EGORefreshTableTailView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view{
    
	[self headerRefData];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view{
	
	//return _reloading; // should return if data source model is reloading
    return _HeaderReloading;
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}




#pragma mark - Cell delegate

- (void)toBabyTimelineView:(id)sender{
    
}



-(IBAction)toUserView:(id)sender{
    
    
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) {
        return;
    }
    
    UIButton *button = (UIButton *)sender;
    
    PersonalViewController *ViewController = [[PersonalViewController alloc]initWithUserId:button.tag];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [self.navigationController pushViewController:ViewController animated:YES];

    [ViewController release];
}



#pragma mark--
#pragma mark 滑动相册


- (void)toPhotoBook:(NSArray *)images{
    
       
    
   DiaryPhotoBrowseViewController *viewController = [[DiaryPhotoBrowseViewController alloc] initWithImages:images  dateArray:nil page:0 localImageNum:0 isPersonalTimeline:NO];    
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:viewController];
    
    
      
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [self.navigationController presentModalViewController:nav animated:YES];
    
    [viewController release];
    [nav release];
    
}



- (IBAction)cancelInviteAction:(id)sender
{
    [selFamilyRoleView removeFromSuperview];
    
}


#pragma mark -
#pragma mark UIPickerView Datasource Delegate

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (familyRoleArray != nil) {
        CLog(@"familyRoleArray %@", familyRoleArray);
        return [self.familyRoleArray count];
    }
    else{
        return 0;
    }
    
}


#pragma mark -
#pragma mark UIPickerViewDelegate



- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    NSString *roleName = [[self.familyRoleArray objectAtIndex:row] objectForKey:@"nickname"];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    label.text = roleName;
    label.font = [UIFont boldSystemFontOfSize:18];
    [label setTextColor:[UIColor blackColor]];
    [label setTextAlignment:UITextAlignmentCenter];
    [label setBackgroundColor:[UIColor clearColor]];
    
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    CLog(@"Sel role %@", [[self.familyRoleArray objectAtIndex:row] objectForKey:@"nickname"]);
    
    familyRoleId = row +1;
    
    
}



#pragma  mark 发送私信- 
- (IBAction)sendLetter:(id)sender{
    
    [textView becomeFirstResponder];
   
    
}



#pragma mark--
#pragma  mark GroingTextView methord

- (void)initGrowingTextView{
    
    containerView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame), 320, 50)];
    //
    containerView.backgroundColor = [UIColor redColor];
    
    
	textView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(5, 10, 248, 50)];
    textView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    
	textView.minNumberOfLines = 1;
	textView.maxNumberOfLines = 6;
	textView.returnKeyType = UIReturnKeyGo; //just as an example
	textView.font = [UIFont systemFontOfSize:15.0f];
	textView.delegate = self;
    textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    
    
    textView.backgroundColor = [UIColor whiteColor];
    
    // textView.text = @"test\n\ntest";
	// textView.animateHeightChange = NO; //turns off animation
    
    
    [self.view insertSubview:containerView aboveSubview:self.myTableView];
	
    UIImage *rawEntryBackground = [UIImage imageNamed:@"MessageEntryInputField.png"];
    UIImage *entryBackground = [rawEntryBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *entryImageView = [[[UIImageView alloc] initWithImage:entryBackground] autorelease];
        
    entryImageView.frame = CGRectMake(5, 0, 248, 50);
    entryImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    UIImage *rawBackground = [UIImage imageNamed:@"MessageEntryBackground.png"];
    UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:background] autorelease];
    imageView.frame = CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    // view hierachy
    [containerView addSubview:imageView];
    [containerView addSubview:textView];
    [containerView addSubview:entryImageView];
    
    //发送
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
	UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	doneBtn.frame = CGRectMake(containerView.frame.size.width - 69, 12, 63, 27);
    doneBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
	[doneBtn setTitle:@"发送" forState:UIControlStateNormal];
    
    [doneBtn setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
    doneBtn.titleLabel.shadowOffset = CGSizeMake (0.0, -1.0);
    doneBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    
    [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[doneBtn addTarget:self action:@selector(resignTextView) forControlEvents:UIControlEventTouchUpInside];
    [doneBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [doneBtn setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
	[containerView addSubview:doneBtn];
    
    
    containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    
}

-(void)resignTextView
{
    [self postLetter:nil];
    textView.text = @"";
    
	[textView resignFirstResponder];
}


- (IBAction)backGroundTap{
    
    [textView resignFirstResponder];
    textView.text = @"";
    
}


//Code from Brett Schumann
-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
	CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
       
    
    containerFrame.origin.y = CGRectGetHeight(self.view.frame) - (keyboardBounds.size.height + containerFrame.size.height);
    
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
	containerView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
    
    //backGround button
    
    backGoundButton.hidden = NO;
    
    
}

-(void) keyboardWillHide:(NSNotification *)note{
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
	
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
    containerFrame.origin.y = CGRectGetHeight(self.view.frame);
    
    // containerFrame.origin.y = 380;
	
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
	// set views with new info
	containerView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
    
    //backGroundButton
    backGoundButton.hidden = YES;
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect r = containerView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
	containerView.frame = r;
}


-(IBAction)backGroundTap:(id)sender{
    
    [textView resignFirstResponder];
   
    
}

#pragma mark ---
- (IBAction)myAttention:(id)sender{  
    FollowerViewController *con = [[FollowerViewController alloc]initWithUserID:userId followType:1];
    [self.navigationController pushViewController:con animated:YES];
    [con release];
    

    
}

- (IBAction)myFans:(id)sender{
    
   // int userId = [[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
    FollowerViewController *con = [[FollowerViewController alloc]initWithUserID:userId followType:2];
    [self.navigationController pushViewController:con animated:YES];
    [con release];
    
}

- (IBAction)myPrivateLetter:(id)sender{
    
    int selfuserId = [[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
   
    
    if ( selfuserId == self.userId) {
        
        PersonalLetterViewController *con = [[PersonalLetterViewController alloc]init];
        [self.navigationController pushViewController:con animated:YES];
        [con release];
    }
    else{
        LetterDetailViewController *con = [[LetterDetailViewController alloc]initWithTitle:userDisplayName fid:[NSString stringWithFormat:@"%d",self.userId]];
        [self.navigationController pushViewController:con animated:YES];
        [con release];
    }
    
}

@end
